package com.guducat.collegeWeb.mapper;

import com.guducat.collegeWeb.entity.UserData;
import com.guducat.collegeWeb.entity.UserDataSyncLog;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 用户数据Mapper接口
 */
@Mapper
public interface UserDataMapper {

    // ==================== UserData 相关操作 ====================

    /**
     * 插入用户数据
     */
    @Insert("INSERT INTO user_data (user_id, data_type, news_id, news_title, news_url, news_category, news_section, extra_data, create_time, update_time) " +
            "VALUES (#{userId}, #{dataType}, #{newsId}, #{newsTitle}, #{newsUrl}, #{newsCategory}, #{newsSection}, #{extraData,typeHandler=com.guducat.collegeWeb.config.JsonTypeHandler}, #{createTime}, #{updateTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertUserData(UserData userData);

    /**
     * 批量插入用户数据（用于同步上传）
     */
    @Insert("<script>" +
            "INSERT INTO user_data (user_id, data_type, news_id, news_title, news_url, news_category, news_section, extra_data, create_time, update_time) VALUES " +
            "<foreach collection='list' item='item' separator=','>" +
            "(#{item.userId}, #{item.dataType}, #{item.newsId}, #{item.newsTitle}, #{item.newsUrl}, #{item.newsCategory}, #{item.newsSection}, " +
            "#{item.extraData,typeHandler=com.guducat.collegeWeb.config.JsonTypeHandler}, #{item.createTime}, #{item.updateTime})" +
            "</foreach>" +
            "</script>")
    int batchInsertUserData(@Param("list") List<UserData> userDataList);

    /**
     * 更新用户数据
     */
    @Update("UPDATE user_data SET news_title = #{newsTitle}, news_url = #{newsUrl}, news_category = #{newsCategory}, news_section = #{newsSection}, " +
            "extra_data = #{extraData,typeHandler=com.guducat.collegeWeb.config.JsonTypeHandler}, update_time = #{updateTime} " +
            "WHERE id = #{id}")
    int updateUserData(UserData userData);

    /**
     * 删除用户数据
     */
    @Delete("DELETE FROM user_data WHERE id = #{id}")
    int deleteUserData(Long id);

    /**
     * 根据用户ID和数据类型删除数据
     */
    @Delete("DELETE FROM user_data WHERE user_id = #{userId} AND data_type = #{dataType}")
    int deleteUserDataByType(@Param("userId") Integer userId, @Param("dataType") String dataType);

    /**
     * 根据用户ID、数据类型和文章ID删除数据
     */
    @Delete("DELETE FROM user_data WHERE user_id = #{userId} AND data_type = #{dataType} AND news_id = #{newsId}")
    int deleteUserDataByNews(@Param("userId") Integer userId, @Param("dataType") String dataType, @Param("newsId") Integer newsId);

    /**
     * 查询用户数据
     */
    @Select("SELECT * FROM user_data WHERE id = #{id}")
    @Results(id = "userDataResultMap", value = {
            @Result(property = "id", column = "id", id = true),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "dataType", column = "data_type"),
            @Result(property = "newsId", column = "news_id"),
            @Result(property = "newsTitle", column = "news_title"),
            @Result(property = "newsUrl", column = "news_url"),
            @Result(property = "newsCategory", column = "news_category"),
            @Result(property = "newsSection", column = "news_section"),
            @Result(property = "extraData", column = "extra_data", typeHandler = com.guducat.collegeWeb.config.JsonTypeHandler.class),
            @Result(property = "createTime", column = "create_time"),
            @Result(property = "updateTime", column = "update_time")
    })
    UserData findById(Long id);

    /**
     * 根据用户ID和数据类型查询数据
     */
    @Select("SELECT * FROM user_data WHERE user_id = #{userId} AND data_type = #{dataType} ORDER BY create_time DESC")
    @ResultMap("userDataResultMap")
    List<UserData> findByUserIdAndType(@Param("userId") Integer userId, @Param("dataType") String dataType);

    /**
     * 根据用户ID查询所有数据
     */
    @Select("SELECT * FROM user_data WHERE user_id = #{userId} ORDER BY data_type, create_time DESC")
    @ResultMap("userDataResultMap")
    List<UserData> findByUserId(Integer userId);

    /**
     * 根据用户ID、数据类型和文章ID查询数据
     */
    @Select("SELECT * FROM user_data WHERE user_id = #{userId} AND data_type = #{dataType} AND news_id = #{newsId}")
    @ResultMap("userDataResultMap")
    UserData findByUserIdAndTypeAndNews(@Param("userId") Integer userId, @Param("dataType") String dataType, @Param("newsId") Integer newsId);

    /**
     * 根据用户ID和数据类型查询数据（分页）
     */
    @Select("SELECT * FROM user_data WHERE user_id = #{userId} AND data_type = #{dataType} " +
            "ORDER BY create_time DESC LIMIT #{offset}, #{limit}")
    @ResultMap("userDataResultMap")
    List<UserData> findByUserIdAndTypeWithPaging(@Param("userId") Integer userId, @Param("dataType") String dataType,
                                                  @Param("offset") Integer offset, @Param("limit") Integer limit);

    /**
     * 统计用户数据数量
     */
    @Select("SELECT COUNT(*) FROM user_data WHERE user_id = #{userId} AND data_type = #{dataType}")
    int countByUserIdAndType(@Param("userId") Integer userId, @Param("dataType") String dataType);

    /**
     * 根据时间范围查询用户数据
     */
    @Select("SELECT * FROM user_data WHERE user_id = #{userId} AND data_type = #{dataType} " +
            "AND create_time >= #{startTime} AND create_time <= #{endTime} ORDER BY create_time DESC")
    @ResultMap("userDataResultMap")
    List<UserData> findByUserIdAndTypeAndTimeRange(@Param("userId") Integer userId, @Param("dataType") String dataType,
                                                    @Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime);

    /**
     * 检查数据是否存在
     */
    @Select("SELECT COUNT(*) > 0 FROM user_data WHERE user_id = #{userId} AND data_type = #{dataType} AND news_id = #{newsId}")
    boolean existsByUserIdAndTypeAndNews(@Param("userId") Integer userId, @Param("dataType") String dataType, @Param("newsId") Integer newsId);

    // ==================== UserDataSyncLog 相关操作 ====================

    /**
     * 插入同步日志
     */
    @Insert("INSERT INTO user_data_sync_log (user_id, sync_type, data_type, sync_count, conflict_count, success_count, " +
            "client_version, sync_status, error_message, sync_time) " +
            "VALUES (#{userId}, #{syncType}, #{dataType}, #{syncCount}, #{conflictCount}, #{successCount}, " +
            "#{clientVersion}, #{syncStatus}, #{errorMessage}, #{syncTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertSyncLog(UserDataSyncLog syncLog);

    /**
     * 更新同步日志
     */
    @Update("UPDATE user_data_sync_log SET sync_count = #{syncCount}, conflict_count = #{conflictCount}, " +
            "success_count = #{successCount}, sync_status = #{syncStatus}, error_message = #{errorMessage} " +
            "WHERE id = #{id}")
    int updateSyncLog(UserDataSyncLog syncLog);

    /**
     * 查询用户同步日志
     */
    @Select("SELECT * FROM user_data_sync_log WHERE user_id = #{userId} ORDER BY sync_time DESC LIMIT #{limit}")
    List<UserDataSyncLog> findSyncLogsByUserId(@Param("userId") Integer userId, @Param("limit") Integer limit);

    /**
     * 查询最近的同步时间
     */
    @Select("SELECT MAX(sync_time) FROM user_data_sync_log WHERE user_id = #{userId} AND sync_type = #{syncType} AND sync_status = 'success'")
    LocalDateTime findLastSuccessfulSyncTime(@Param("userId") Integer userId, @Param("syncType") String syncType);

    // ==================== 统计查询 ====================

    /**
     * 获取用户数据统计
     */
    @Select("SELECT data_type, COUNT(*) as count, MIN(create_time) as first_time, MAX(create_time) as last_time " +
            "FROM user_data WHERE user_id = #{userId} GROUP BY data_type")
    List<Map<String, Object>> getUserDataStats(Integer userId);

    /**
     * 清理过期历史记录
     */
    @Delete("DELETE FROM user_data WHERE user_id = #{userId} AND data_type = 'history' " +
            "AND create_time < DATE_SUB(NOW(), INTERVAL #{keepDays} DAY)")
    int cleanExpiredHistory(@Param("userId") Integer userId, @Param("keepDays") Integer keepDays);
}
